package it.sportingnola.soccernotes;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Html;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class SoccerNotes extends ListActivity {
    public static final int ACTIVITY_CREATE=0;
    public static final int ACTIVITY_EDIT=1;
    public static final int TEAM_EDIT=2; // terza attività
    public static final int SUBST_EDIT=3; // quarta attività
    public static final int GOAL_EDIT=4; // quinta attività
    public static final int CARD_EDIT=5; // sesta attività
    public static final int ACTION_EDIT=6; // sesta attività
    public static final int CONFIG_EDIT=7;
    private static final int INSERT_ID=1; // inserimento
    private static final int ABOUT_ID=2; // informazioni
    private static final int CONFIG_ID=3; // inserimento
    private static final int MAIL_ID=CONFIG_ID + 1; // invio email
    private static final int DELETE_ID=MAIL_ID + 1;// cancellazione
    private DbHelper dbHelper;
    private final String[] from=new String[]{DbHelper.KEY_TITOLI };
    private final int[] to=new int[]{R.id.text1 };
    private int default_nr_players;
    private String mailTo;
    private String mailFrom;
    private long to_delete;

    public void createNote(View view) {
	Intent i=new Intent(this, NoteEdit.class);
	i.putExtra(Const.Cronache.KEY_ROWID, 0);
	i.putExtra(Const.Config.KEY_DEFAULT_PL_NUMBER, default_nr_players);
	startActivityForResult(i, ACTIVITY_CREATE);
    }

    private void editConf() {
	Intent i=new Intent(this, ConfEdit.class);
	startActivityForResult(i, CONFIG_EDIT);
    }

    /**
     * Recupera i dati dal db e riempe la lista
     */
    private void fillData() {
	Cursor cronCursor=dbHelper.fetchAllTitles();
	startManagingCursor(cronCursor);
	SimpleCursorAdapter cAdapter=new SimpleCursorAdapter(this, R.layout.notes_row, cronCursor, from, to);
	setListAdapter(cAdapter);
	fillDefault();
    }

    private void fillDefault() {
	Cursor confCursor=dbHelper.cercaConfig();
	startManagingCursor(confCursor);
	confCursor.moveToFirst();
	default_nr_players=confCursor.getInt(confCursor.getColumnIndex(Const.Config.KEY_DEFAULT_PL_NUMBER));
	setMailFrom(confCursor.getString(confCursor.getColumnIndex(Const.Config.KEY_MAIL_FROM)));
	mailTo=confCursor.getString(confCursor.getColumnIndex(Const.Config.KEY_MAIL_TO));
    }

    /**
     * La funziona che genera il testo della mail contenente la cronaca in HTML
     * 
     * @param id: l'id della cronaca
     * @return una stringa contenente l'HTML desiderato
     */
    private String generaCronacaHTML(Long id) {
	StringBuffer ret=new StringBuffer("");
	Cursor c=dbHelper.recuperaCronaca(id);
	startManagingCursor(c);
	if (c.moveToFirst()) {
	    String htName=c.getString(c.getColumnIndex(Const.Cronache.KEY_TEAM1));
	    String ftName=c.getString(c.getColumnIndex(Const.Cronache.KEY_TEAM2));
	    String tName="";
	    ret.append("<h1>" + htName + " - " + ftName + " "
		+ c.getString(c.getColumnIndex(Const.Cronache.KEY_RESULT)) + "</h1><h2>"
		+ c.getString(c.getColumnIndex(Const.Cronache.KEY_TITLE)) + "</h2><h2>" + getString(R.string.teams)
		+ "</h1>\n");
	    Cursor cApp=dbHelper.cercaSquadra(Const.HOME_TEAM, id);
	    startManagingCursor(cApp);
	    if (cApp.moveToFirst()) {
		ret.append("<h3>" + c.getString(c.getColumnIndex(Const.Cronache.KEY_TEAM1)) + "</h3> ");
		do {
		    if (cApp.getInt(cApp.getColumnIndex(Const.Players.KEY_IS_MR)) == 0) {
			ret.append(cApp.getString(cApp.getColumnIndex(Const.Players.KEY_NR)) + ") "
			    + cApp.getString(cApp.getColumnIndex(Const.Players.KEY_NAME)) + ", ");
		    }
		    else {
			ret.append("<br><b>" + cApp.getString(cApp.getColumnIndex(Const.Players.KEY_NR)) + "</b>: "
			    + cApp.getString(cApp.getColumnIndex(Const.Players.KEY_NAME)));
		    }
		}
		while (cApp.move(1));
		ret.append("<br>\n");
	    }
	    cApp=dbHelper.cercaSquadra(Const.FOREIGN_TEAM, id);
	    if (cApp.moveToFirst()) {
		ret.append("<h3>" + c.getString(c.getColumnIndex(Const.Cronache.KEY_TEAM2)) + "</h3> ");
		do {
		    if (cApp.getInt(cApp.getColumnIndex(Const.Players.KEY_IS_MR)) == 0) {
			ret.append(cApp.getString(cApp.getColumnIndex(Const.Players.KEY_NR)) + ") "
			    + cApp.getString(cApp.getColumnIndex(Const.Players.KEY_NAME)) + ", ");
		    }
		    else {
			ret.append("<br><b>" + cApp.getString(cApp.getColumnIndex(Const.Players.KEY_NR)) + "</b>: "
			    + cApp.getString(cApp.getColumnIndex(Const.Players.KEY_NAME)));
		    }
		}
		while (cApp.move(1));
		ret.append("<br>\n");
	    }
	    cApp=dbHelper.cercaSubst(id);
	    if (cApp.moveToFirst()) {
		ret.append("<h2>" + getString(R.string.substitutions) + "</h2>\n");
		do {
		    tName=cApp.getInt(cApp.getColumnIndex(Const.Subst.KEY_TEAM)) == Const.HOME_TEAM ? htName : ftName;
		    ret.append(cApp.getString(cApp.getColumnIndex(Const.Subst.KEY_MIN))
			+ " - "
			+ getResources().getTextArray(R.array.halfs)[cApp.getInt(cApp
			    .getColumnIndex(Const.Subst.KEY_HALF))] + " (" + tName + ") : "
			+ cApp.getString(cApp.getColumnIndex(Const.Subst.KEY_NAME_PLAYER_IN)) + " -> "
			+ cApp.getString(cApp.getColumnIndex(Const.Subst.KEY_NAME_PLAYER_OUT)) + "<br>");
		}
		while (cApp.moveToNext());
	    }
	    cApp=dbHelper.cercaGoal(id);
	    String scorer="";
	    if (cApp.moveToFirst()) {
		ret.append("<h2>" + getString(R.string.goals) + "</h2>");
		do {
		    scorer=cApp.getString(cApp.getColumnIndex(Const.Goals.KEY_NAME_PLAYER));
		    if (cApp.getShort(cApp.getColumnIndex(Const.Goals.KEY_IS_AUTO)) == 1) {
			scorer+=" (" + getString(R.string.short_own_goal) + ")";// autogol
		    }
		    if (cApp.getShort(cApp.getColumnIndex(Const.Goals.KEY_IS_PENALTY)) == 1) {
			scorer+=" (" + getString(R.string.short_penalty) + ")";// rigore
		    }
		    tName=cApp.getInt(cApp.getColumnIndex(Const.Goals.KEY_TEAM)) == Const.HOME_TEAM ? htName : ftName;
		    scorer+=" (" + tName + ")";
		    ret.append(cApp.getString(cApp.getColumnIndex(Const.Goals.KEY_MIN))
			+ " - "
			+ getResources().getTextArray(R.array.halfs)[cApp.getInt(cApp
			    .getColumnIndex(Const.Goals.KEY_HALF))] + ": " + scorer + "<br>");

		}
		while (cApp.moveToNext());
	    }
	    cApp=dbHelper.cercaCard(id);
	    if (cApp.moveToFirst()) {
		ret.append("<h2>" + getString(R.string.cards) + "</h2>\n");
		do {
		    tName=cApp.getInt(cApp.getColumnIndex(Const.Cards.KEY_TEAM)) == Const.HOME_TEAM ? htName : ftName;
		    ret.append(cApp.getString(cApp.getColumnIndex(Const.Cards.KEY_MIN))
			+ " - "
			+ getResources().getTextArray(R.array.halfs)[cApp.getInt(cApp
			    .getColumnIndex(Const.Cards.KEY_HALF))]
			+ " ("
			+ tName
			+ "): "
			+ cApp.getString(cApp.getColumnIndex(Const.Cards.KEY_NAME_PLAYER))
			+ " ("
			+ getResources().getTextArray(R.array.cards)[cApp.getInt(cApp
			    .getColumnIndex(Const.Cards.KEY_CARD))] + "): "
			+ cApp.getString(cApp.getColumnIndex(Const.Cards.KEY_REASON)) + "<br>");
		}
		while (cApp.moveToNext());
	    }
	    ret.append(getString(R.string.corners) + ": " + c.getString(c.getColumnIndex(Const.Cronache.KEY_CORNER1))
		+ "-" + c.getString(c.getColumnIndex(Const.Cronache.KEY_CORNER2)));
	    ret.append(getString(R.string.fouls) + ": " + c.getString(c.getColumnIndex(Const.Cronache.KEY_FOUL1)) + "-"
		+ c.getString(c.getColumnIndex(Const.Cronache.KEY_FOUL2)));
	    cApp=dbHelper.cercaAction(id);
	    if (cApp.moveToFirst()) {
		ret.append("<h2>" + getString(R.string.actions) + "</h2>");
		do {
		    tName=cApp.getInt(cApp.getColumnIndex(Const.Subst.KEY_TEAM)) == Const.HOME_TEAM ? htName : ftName;
		    ret.append(cApp.getString(cApp.getColumnIndex(Const.Actions.KEY_MIN))
			+ " - "
			+ getResources().getTextArray(R.array.halfs)[cApp.getInt(cApp
			    .getColumnIndex(Const.Actions.KEY_HALF))] + " (" + tName + "): ");

		    ret.append(Util.N2Html(cApp.getString(cApp.getColumnIndex(Const.Actions.KEY_DESCRI))) + "<br>");
		}
		while (cApp.moveToNext());
	    }
	    cApp.close();
	    ret.append("<h3>" + getString(R.string.notes) + "</h3>");
	    ret.append("<b>" + getString(R.string.referee) + "</b>: "
		+ c.getString(c.getColumnIndex(Const.Cronache.KEY_REFEREE)) + "<br>");
	    ret.append("<b>" + getString(R.string.assistents) + "</b>: "
		+ c.getString(c.getColumnIndex(Const.Cronache.KEY_ASSISTENTS)) + "<br>");
	    ret.append("<b>" + c.getString(c.getColumnIndex(Const.Cronache.KEY_PLACE)) + "</b> - "
		+ Util.N2Html(c.getString(c.getColumnIndex(Const.Cronache.KEY_BODY))));
	}
	c.close();
	return Util.db2Html(ret.toString());
    }

    public String getMailFrom() {
	return mailFrom;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
	super.onActivityResult(requestCode, resultCode, intent);
	fillData();
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	    case DELETE_ID:
		AdapterContextMenuInfo info=(AdapterContextMenuInfo) item.getMenuInfo();
		to_delete=info.id;
		AlertDialog.Builder builder=new AlertDialog.Builder(this).setTitle(R.string.delete_entry)
		    .setMessage(R.string.confirm)
		    .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
			    dbHelper.deleteNote(to_delete);
			    fillData();
			}
		    }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
			    dialog.cancel();
			}
		    });
		builder.create();
		builder.show();
		return true;
	    case MAIL_ID:
		sendMail(item);
		return true;
	}
	return super.onContextItemSelected(item);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	// Create the adView
	AdView adView=new AdView(this, AdSize.BANNER, Const.MY_AD_UNIT_ID);
	// Lookup your LinearLayout assuming it’s been given
	// the attribute android:id="@+id/mainLayout"
	LinearLayout layout=(LinearLayout) findViewById(R.id.ads);
	// Add the adView to it
	layout.addView(adView);
	// Initiate a generic request to load it with an ad
	adView.loadAd(new AdRequest());

	dbHelper=new DbHelper(this);
	dbHelper.open();
	fillData();
	registerForContextMenu(getListView());
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	super.onCreateContextMenu(menu, v, menuInfo);
	menu.add(0, MAIL_ID, 0, R.string.menu_mail);
	menu.add(0, DELETE_ID, 1, R.string.menu_delete);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	super.onCreateOptionsMenu(menu);
	menu.add(0, INSERT_ID, 0, R.string.menu_insert);
	menu.add(2, CONFIG_ID, 2, R.string.menu_config);
	menu.add(1, ABOUT_ID, 1, R.string.menu_about);
	return true;
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
	super.onListItemClick(l, v, position, id);
	Intent i=new Intent(this, NoteEdit.class);
	i.putExtra(Const.Players.KEY_CRONACA, id);
	i.putExtra(Const.Config.KEY_DEFAULT_PL_NUMBER, default_nr_players);
	startActivityForResult(i, ACTIVITY_EDIT);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
	switch (item.getItemId()) {
	    case INSERT_ID:
		createNote(null);
		return true;
	    case CONFIG_ID:
		editConf();
		return true;
	    case ABOUT_ID:
		showAbout();
		return true;
	}
	return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onResume() {
	super.onResume();
	fillDefault();
    }

    private void sendMail(MenuItem item) {
	AdapterContextMenuInfo info=(AdapterContextMenuInfo) item.getMenuInfo();
	String email=generaCronacaHTML(info.id);
	Intent emailIntent=new Intent(android.content.Intent.ACTION_SEND);
	emailIntent.setType("text/html");
	emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{mailTo });
	emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, dbHelper.recuperaTitolo(info.id));
	emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
	    Html.fromHtml(new StringBuilder().append(email).toString()));
	startActivity(Intent.createChooser(emailIntent, getString(R.string.email_send)));
    }

    public void setDefNrPl(int value) {
	default_nr_players=value;
    }

    public void setMailFrom(String mailFrom) {
	this.mailFrom=mailFrom;
    }

    public void setMailTo(String value) {
	mailTo=value;
    }

    private void showAbout() {
	AlertDialog.Builder builder=new AlertDialog.Builder(this);
	builder.setMessage(R.string.about_msg).setCancelable(true).setTitle(R.string.about_title)
	    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int id) {
		    dbHelper.deleteNote(id);
		    fillData();
		}
	    });
	builder.create();
	builder.show();
    }

}